package com.taxsearch.controller.checkin;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.taxsearch.service.RzCompare;
import com.taxsearch.service.linsa.CheckInService;
import com.taxsearch.service.room.RoomService;
import com.taxsearch.util.AgeCalculation;
import com.taxsearch.util.DbUtil;
import com.taxsearch.util.Json;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @author 高敏
 * @version V1.0
 * @Title:CheckInController
 * @Description: 登记入住控制器（境内）
 * @date 2018年8月14日
 */
@Controller
@RequestMapping("/HotelAndroid")
public class CheckInController {
    private static Logger logger = Logger.getLogger(CheckInController.class);
    @Resource
    private CheckInService checkInService;
    @Resource
    private RoomService roomService;
    @Autowired
    RzCompare rzCompare;

    /**
     * 查询民族列表（境内）
     *
     * @return
     */
    @RequestMapping("/selectNation.do")
    @ResponseBody
    public Json selectNation() {
        Json json = new Json();
        try {
            //切换数据源,切换到无证审批数据库
            DbUtil.setDb("3");
            List<HashMap<String, String>> list = checkInService.selectNation();
            //切换回默认数据库
            DbUtil.setDb("1");
            logger.info("成功查询民族列表！");
            json.setObj(list);
            json.setMsg("成功查询民族列表！");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("selectNation.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询证件类型（境内）
     *
     * @return
     */
    @RequestMapping("/selectIDType.do")
    @ResponseBody
    public Json selectIDType() {
        Json json = new Json();
        try {
            DbUtil.setDb("1");
            List<HashMap<String, String>> list = checkInService.selectIDType();
            logger.info("成功查询境内证件类型！");
            json.setObj(list);
            json.setMsg("成功查询境内证件类型！");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("selectIDType.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询省份（境内）
     *
     * @return
     */
    @RequestMapping("/selectProvince.do")
    @ResponseBody
    public Json selectProvince() {
        Json json = new Json();
        try {
            //切换数据源,切换到无证审批数据库
            DbUtil.setDb("3");
            List<HashMap<String, String>> list = checkInService.selectProvince();
            //切换回默认数据库
            DbUtil.setDb("1");
            logger.info("成功查询省份列表！");
            json.setObj(list);
            json.setMsg("成功查询省份列表！");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("selectProvince.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询市（境内）
     *
     * @return
     */
    @RequestMapping("/selectCity.do")
    @ResponseBody
    public Json selectCity(HttpServletRequest request) {
        Json json = new Json();
        try {
            String area = request.getParameter("area");
            //area="湖北省";
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("NUM", area.length());
            map.put("DI_CVALUE", area);
            //切换数据源,切换到无证审批数据库
            DbUtil.setDb("3");
            List<HashMap<String, String>> list = checkInService.selectCity(map);
            //切换回默认数据库
            DbUtil.setDb("1");
            logger.info("成功查询市列表！");
            json.setObj(list);
            json.setMsg("成功查询市列表！");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("selectCity.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询县/地区（境内）
     *
     * @return
     */
    @RequestMapping("/selectArea.do")
    @ResponseBody
    public Json selectArea(HttpServletRequest request) {
        Json json = new Json();
        try {
            String area = request.getParameter("area");
            //area="湖北省黄冈市";
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("NUM", area.length());
            map.put("DI_CVALUE", area);
            //切换数据源,切换到无证审批数据库
            DbUtil.setDb("3");
            List<HashMap<String, String>> list = checkInService.selectArea(map);
            //切换回默认数据库
            DbUtil.setDb("1");
            logger.info("成功查询县/地区列表！");
            json.setObj(list);
            json.setMsg("成功查询县/地区列表！");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("selectArea.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 处理无证审批 插入无证审批内容，等待三分钟查询无证审批结果返回给前台 当三分钟后审核成功则入住，不成功返回信息
     * 注：老版本，已不用
     * @return
     */
	/*@RequestMapping("/insertExamineOld.do")
	@ResponseBody
	public Json insertExamineOld(HttpServletRequest request) {
		Json json = new Json();
		try {
			// 获取前端的值
			String name = request.getParameter("name");
			String sex = request.getParameter("sex");
			String nation = request.getParameter("nation");
			String birth = request.getParameter("birth");
			String IDType = request.getParameter("IDType");
			String IDNumber = request.getParameter("IDNumber");
			String address = request.getParameter("address");
			String time = request.getParameter("time");
			String roomNumber = request.getParameter("roomNumber");
			String hotelCode = request.getParameter("hotelCode");
			String photo = request.getParameter("photo");
			String tel = request.getParameter("tel");
			String xzqh_id = request.getParameter("xzqh_id");
			
			name = "高敏";
			sex = "1";
			nation = "01";
			birth = "1994-05-01";
			IDType = "11";
			IDNumber = "421182199405013329";
			address = "111";
			time = "2018-09-12 12:34:56";
			roomNumber = "101";
			hotelCode = "5101220060";
			photo = "111";
			tel = "17345764025";
			xzqh_id = "421182";
			
			//判断当前人是否在该房间已入住
			HashMap<String, Object> map2 = new HashMap<String, Object>();
			map2.put("DJ_ZHENGJIANHAOMA", IDNumber);
			map2.put("DJ_LVGUANDAIMA", hotelCode);
			HashMap<String, String> hashMap2 = checkInService.selectDoYouCheckIn(map2);
			HashMap<String, String> hashMap3 = checkInService.selectDoYouCheckIn(map2);
			if(hashMap2.get("NUM").equals("false")||hashMap3.get("NUM").equals("false")){
				json.setMsg("该旅馆你已入住，请勿重复入住!");
				json.setSuccess(false);
				logger.info("该旅馆你已入住，请勿重复入住!");
				return json;
			}
			
			// base64格式转成Blob二进制
			byte[] photoBytes = null;
			try {
				photoBytes = getStringImage(photo);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			
			//查询当前旅馆派出所编码
			HashMap<String, String> hashMap1 = checkInService.selectPAICHUSUOBM(hotelCode);
			String PAICHUSUOBM = hashMap1.get("PAICHUSUOBM");

			String num = (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10);
			// 插入无证审批内容
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("DJ_LVKEDAIMA", hotelCode + time.replace("-", "").substring(0, 8) + "0" + num);
			map.put("DJ_XINGMING", name);
			map.put("DJ_XINGBIE", sex);
			map.put("DJ_MINZU", nation);
			map.put("DJ_CHUSHENGRIQI", birth);
			map.put("DJ_ZHENGJIANLEIXING", IDType);
			map.put("DJ_ZHENGJIANHAOMA", IDNumber);
			map.put("DJ_SHENGSHIXIAN", xzqh_id);
			map.put("DJ_XIANGZHI", address);
			map.put("DJ_RUZHUSHIJIAN", time);
			map.put("DJ_RUZHUFANGHAO", roomNumber);
			map.put("DJ_TUIFANGSHIJIAN", time);
			map.put("DJ_ZHAOPIAN", photoBytes);
			map.put("DJ_LVGUANDAIMA", hotelCode);
			map.put("BUPLOAD", "0");
			map.put("DJ_PAICHUSUO", PAICHUSUOBM);
			map.put("RECORDSNO", hotelCode + time.replace("-", "").replace(":", "").replace(" ", "") + num);
			map.put("STATIONID", hotelCode);
			logger.info("插入无证审批信息" + map);
			
			//切换数据源,切换到无证审批数据库
			DbUtil.setDb("3");
			int res = checkInService.insertExamine(map);
			logger.info("成功插入无证审批信息" + res);

			// 查询无证审批返回内容
			String RECORDSNO = hotelCode + time.replace("-", "").replace(":", "").replace(" ", "") + num;
			Thread.currentThread();
			// 等待三分钟执行
			List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
			for(int n=0;n<12;n++){
				Thread.sleep(1000*10);
				list = checkInService.selectExamineBack(RECORDSNO);
				Object SP_RESULT = list.get(0).get("SP_RESULT");
				Object SP_TAG = list.get(0).get("SP_TAG");
				Object ISEXPORT = list.get(0).get("ISEXPORT");
				if (SP_RESULT!=null&&SP_TAG!=null&&ISEXPORT!=null&&
						String.valueOf(SP_RESULT).equals("1")&&Integer.valueOf(String.valueOf(SP_TAG))>3&&String.valueOf(ISEXPORT).equals("1")) {
					break;
				}
			}
			
			//切换回默认数据库
			DbUtil.setDb("1");
			logger.info("查询无证审批返回内容" + list);
			Object SP_RESULT = list.get(0).get("SP_RESULT");
			Object SP_TAG = list.get(0).get("SP_TAG");
			Object ISEXPORT = list.get(0).get("ISEXPORT");
			if (SP_RESULT!=null&&SP_TAG!=null&&ISEXPORT!=null&&
					String.valueOf(SP_RESULT).equals("1")&&Integer.valueOf(String.valueOf(SP_TAG))>3&&String.valueOf(ISEXPORT).equals("1")) {
				// 审批成功,插入无证入住信息
				HashMap<String, Object> sub_map = new HashMap<String, Object>();
				sub_map.put("DJ_LVKEDAIMA", hotelCode + String.valueOf(generate(12)));
				sub_map.put("DJ_XINGMING", name);
				sub_map.put("DJ_XINGBIE", sex);
				sub_map.put("DJ_MINZU", nation);
				sub_map.put("DJ_CHUSHENGRIQI", birth);
				sub_map.put("DJ_ZHENGJIANLEIXING", IDType);
				sub_map.put("DJ_ZHENGJIANHAOMA", IDNumber);
				sub_map.put("DJ_SHENGSHIXIAN", xzqh_id);
				sub_map.put("DJ_XIANGZHI", address);
				sub_map.put("DJ_RUZHUSHIJIAN", time);
				sub_map.put("DJ_RUZHUFANGHAO", roomNumber);
				sub_map.put("DJ_ZHAOPIAN", "123");
				sub_map.put("DJ_UPZHAOPIAN", "123");
				sub_map.put("DJ_LVGUANDAIMA", hotelCode);
				sub_map.put("BUPLOAD", "0");
				sub_map.put("RECORDSNO", hotelCode + time.replace("-", "").replace(":", "").replace(" ", "") + num);
				sub_map.put("STATIONID", hotelCode);
				sub_map.put("PACKNAME",  hotelCode  + time.replace("-", "").replace(":", "").replace(" ", "") + num);
				sub_map.put("TEL", tel);
				logger.info("插入无证入住信息" + sub_map);
				//int sub_res = checkInService.insertCheckIn(sub_map);
				int sub_res = DbbUtil.insertCheckIn(sub_map);
				logger.info("成功插入无证入住信息" + sub_res);
				
				// 审批成功,更改预订状态为已入住
				String bookTime = request.getParameter("bookTime");
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhh24mmss");// 设置日期格式
				String date = (df.format(new Date())).substring(0, 8);// new Date()为获取当前系统时间
				if(bookTime!=null&&bookTime!=""){
					bookTime=bookTime.replace("-", "").substring(0, 8);
				}else{
					bookTime=date;
				}
				HashMap<String, Object> sub_map1 = new HashMap<String, Object>();
				sub_map1.put("STATIONID", hotelCode);
				sub_map1.put("ROOMNUMBER",  roomNumber);
				sub_map1.put("CHECKINTIME",  bookTime);
				logger.info("更改预订状态" + sub_map1);
				//int sub_res1 = checkInService.updateBookRoom(sub_map1);
				int sub_res1 = DbbUtil.updateYuDing(hotelCode, roomNumber);
				logger.info("成功更改预订状态" + sub_res1);
				
				// Blob二进制转成base64格式
				byte[] blob = DBUtil.getByteBlob(RECORDSNO);
				if(blob!=null){
					String DJ_UPZHAOPIAN = getImageString(blob);
					list.get(0).put("DJ_UPZHAOPIAN", DJ_UPZHAOPIAN);
				}
				if(sub_res==1){
					json.setObj(list);
					json.setMsg("审批成功，已入住！");
					logger.info("审批成功，已入住！");
					json.setSuccess(true);
				}else{
					json.setObj(list);
					json.setMsg("审批失败！");
					logger.info("审批失败！");
					json.setSuccess(false);
				}
				
			} else {
				// Blob二进制转成base64格式
				byte[] blob = DBUtil.getByteBlob(RECORDSNO);
				if(blob!=null){
					String DJ_UPZHAOPIAN = getImageString(blob);
					list.get(0).put("DJ_UPZHAOPIAN", DJ_UPZHAOPIAN);
				}
				json.setObj(list);
				json.setMsg("审批失败!");
				json.setSuccess(false);
				logger.info("审批失败!");
			}
		} catch (Exception e) {
			json.setMsg("审批失败,请联系管理员！");
			json.setSuccess(false);
			logger.info("审批失败,请联系管理员！");
			e.printStackTrace();
		}
		return json;
	}*/

    /**
     * 处理无证审批 插入无证审批内容，插入入住信息（境内）
     *
     * @return
     */
    @RequestMapping("/insertExamine.do")
    @ResponseBody
    public Json insertExamine(HttpServletRequest request) {
        Json json = new Json();
        try {
            // 获取前端的值
            String name = request.getParameter("name");
            String sex = request.getParameter("sex");
            String nation = request.getParameter("nation");
            String birth = request.getParameter("birth");
            String IDType = request.getParameter("IDType");
            String IDNumber = request.getParameter("IDNumber");
            String address = request.getParameter("address");
            String time = request.getParameter("time");
            String roomNumber = request.getParameter("roomNumber");
            String hotelCode = request.getParameter("hotelCode");
            String photo = request.getParameter("photo");
            String tel = request.getParameter("tel");
            String xzqh_id = request.getParameter("xzqh_id");
			
			/*name = "高敏";
			sex = "1";
			nation = "01";
			birth = "1994-05-01";
			IDType = "11";
			IDNumber = "421182199405013329";
			address = "111";
			time = "2018-09-12 12:34:56";
			roomNumber = "101";
			hotelCode = "5101220060";
			photo = "111";
			tel = "17345764025";
			xzqh_id = "421182";*/

            DbUtil.setDb("1");
            //判断当前人是否在该房间已入住
            HashMap<String, Object> map2 = new HashMap<String, Object>();
            map2.put("DJ_ZHENGJIANHAOMA", IDNumber);
            map2.put("DJ_LVGUANDAIMA", hotelCode);
            HashMap<String, String> hashMap2 = checkInService.selectDoYouCheckIn(map2);
            HashMap<String, String> hashMap3 = checkInService.selectDoYouCheckIn(map2);
            if (hashMap2.get("NUM").equals("false") || hashMap3.get("NUM").equals("false")) {
                json.setMsg("该旅馆你已入住，请勿重复入住!");
                json.setSuccess(false);
                logger.info("该旅馆你已入住，请勿重复入住!");
                return json;
            }
            boolean flag = roomService.judgeRuzhuPerson(hotelCode, roomNumber);
            if (!flag) {
                json.setMsg("该房间入住人数已满，请换房间入住!");
                json.setSuccess(false);
                logger.info("该房间入住人数已满，请换房间入住!");
                return json;
            }

            // base64格式转成Blob二进制
            byte[] photoBytes = null;
            try {
                photoBytes = getStringImage(photo);
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            //查询当前旅馆派出所编码
            HashMap<String, String> hashMap1 = checkInService.selectPAICHUSUOBM(hotelCode);
            // 如果没有赋值空串
            String PAICHUSUOBM = (null == hashMap1) ? "" : hashMap1.get("PAICHUSUOBM");

            String num = (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10);

            // 插入无证入住信息
            HashMap<String, Object> sub_map = new HashMap<String, Object>();
            sub_map.put("DJ_LVKEDAIMA", hotelCode + String.valueOf(generate(12)));
            sub_map.put("DJ_XINGMING", name);
            sub_map.put("DJ_XINGBIE", sex);
            sub_map.put("DJ_MINZU", nation);
            sub_map.put("DJ_CHUSHENGRIQI", birth);
            sub_map.put("DJ_ZHENGJIANLEIXING", IDType);
            sub_map.put("DJ_ZHENGJIANHAOMA", IDNumber);
            sub_map.put("DJ_SHENGSHIXIAN", xzqh_id);
            sub_map.put("DJ_XIANGZHI", address);
            sub_map.put("DJ_RUZHUSHIJIAN", time);
            sub_map.put("DJ_RUZHUFANGHAO", roomNumber);
            sub_map.put("DJ_ZHAOPIAN", photoBytes);
            sub_map.put("DJ_UPZHAOPIAN", photoBytes);
            sub_map.put("DJ_LVGUANDAIMA", hotelCode);
            sub_map.put("BUPLOAD", "3");
            sub_map.put("RECORDSNO", hotelCode + time.replace("-", "").replace(":", "").replace(" ", "") + num);
            sub_map.put("STATIONID", hotelCode);
            sub_map.put("PACKNAME", hotelCode + time.replace("-", "").replace(":", "").replace(" ", "") + num);
            sub_map.put("TEL", tel);
            sub_map.put("ENTERPRISE_ID", "0");

            /* 2019/1/21 修改,使用一个字段区分是否使用省公司结构上传同步数据*/
            sub_map.put("DJ_TIMAO", "0");//用于同步数据,0:数据有变化,未同步;1:已同步
            logger.info("插入无证入住信息，证件号码为：" + sub_map.get("DJ_ZHENGJIANHAOMA"));
            int sub_res = checkInService.insertCheckIn(sub_map);
            //int sub_res = DbbUtil.insertCheckIn(sub_map);
            logger.info("成功插入无证入住信息" + sub_res);

            // 更改预订状态为已入住
            String bookTime = request.getParameter("bookTime");
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhh24mmss");// 设置日期格式
            String date = (df.format(new Date())).substring(0, 8);// new Date()为获取当前系统时间
            if (bookTime != null && bookTime != "") {
                bookTime = bookTime.replace("-", "").substring(0, 8);
            } else {
                bookTime = date;
            }
            HashMap<String, Object> sub_map1 = new HashMap<String, Object>();
            sub_map1.put("STATIONID", hotelCode);
            sub_map1.put("ROOMNUMBER", roomNumber);
            sub_map1.put("CHECKINTIME", bookTime);
            logger.info("更改预订状态" + sub_map1);
            int sub_res1 = checkInService.updateBookRoom(sub_map1);
            //int sub_res1 = DbbUtil.updateYuDing(hotelCode, roomNumber);
            logger.info("成功更改预订状态" + sub_res1);

            // 插入无证审批内容
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("DJ_LVKEDAIMA", hotelCode + time.replace("-", "").substring(0, 8) + "0" + num);
            map.put("DJ_XINGMING", name);
            map.put("DJ_XINGBIE", sex);
            map.put("DJ_MINZU", nation);
            map.put("DJ_CHUSHENGRIQI", birth);
            map.put("DJ_ZHENGJIANLEIXING", IDType);
            map.put("DJ_ZHENGJIANHAOMA", IDNumber);
            map.put("DJ_SHENGSHIXIAN", xzqh_id);
            map.put("DJ_XIANGZHI", address);
            map.put("DJ_RUZHUSHIJIAN", time);
            map.put("DJ_RUZHUFANGHAO", roomNumber);
            map.put("DJ_TUIFANGSHIJIAN", time);
            map.put("DJ_ZHAOPIAN", photoBytes);
            map.put("DJ_LVGUANDAIMA", hotelCode);
            map.put("BUPLOAD", "0");
            map.put("DJ_PAICHUSUO", PAICHUSUOBM);
            map.put("RECORDSNO", hotelCode + time.replace("-", "").replace(":", "").replace(" ", "") + num);
            map.put("STATIONID", hotelCode);
            logger.info("插入无证审批信息，证件号码为：" + map.get("DJ_ZHENGJIANHAOMA"));

            //切换数据源,切换到无证审批数据库
            DbUtil.setDb("3");
            int res = checkInService.insertExamine(map);
            //切换回默认数据库
            DbUtil.setDb("1");
            logger.info("成功插入无证审批信息" + res);

            json.setMsg("正在审批中！");
            json.setSuccess(true);
            logger.info("正在审批中！");

        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("insertExamine.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 出入有证入住信息（境内）
     *
     * @return
     */
    @RequestMapping("/insertCheckIn.do")
    @ResponseBody
    public Json insertCheckIn(HttpServletRequest request) {
        Json json = new Json();
        try {
            // 获取前端的值
            String name = request.getParameter("name");
            String sex = request.getParameter("sex");
            String nation = request.getParameter("nation");
            String birth = request.getParameter("birth");
            String IDType = request.getParameter("IDType");
            String IDNumber = request.getParameter("IDNumber");
            String address = request.getParameter("address");
            String time = request.getParameter("time");
            String roomNumber = request.getParameter("roomNumber");
            String photo = request.getParameter("photo");
            String IDPhoto = request.getParameter("IDPhoto");
            String hotelCode = request.getParameter("hotelCode");
            String tel = request.getParameter("tel");
            String xzqh_id = request.getParameter("xzqh_id");
            String is_rzsb = request.getParameter("is_rzsb");
            //20211027 jiangf 新增未成年入住功能
            /*--------------------------------------*/
            String guardianName = request.getParameter("jhrxm");
            String guardianIDNumber = request.getParameter("jhrzjh");
            String guardianTel = request.getParameter("jhrdh");
            String residentsRelationship = request.getParameter("tzrgx");
            String is_unreasonable = request.getParameter("gxsfbhl");
            String is_danger = request.getParameter("sfwx");
            String unreasonable_check_in = request.getParameter("bhlrz");
            String other_suspicious_situations = request.getParameter("qtkyqk");
            /*--------------------------------------*/
			
			/*name = "高敏";
			sex = "1";
			nation = "01";
			birth = "1994-05-01";
			IDType = "11";
			IDNumber = "421182199405013329";
			address = "111";
			time = "2018-09-12 12:34:56";
			roomNumber = "101";
			hotelCode = "5101220060";
			photo = "111";
			tel = "17345764025";
			xzqh_id = "421182";
			is_rzsb = "1";*/

            DbUtil.setDb("1");
            //判断当前人是否在该房间已入住
            HashMap<String, Object> map2 = new HashMap<String, Object>();
            map2.put("DJ_ZHENGJIANHAOMA", IDNumber);
            map2.put("DJ_LVGUANDAIMA", hotelCode);
            HashMap<String, String> hashMap2 = checkInService.selectDoYouCheckIn(map2);
            HashMap<String, String> hashMap3 = checkInService.selectDoYouCheckInF(map2);
            if (hashMap2.get("NUM").equals("false") || hashMap3.get("NUM").equals("false")) {
                json.setMsg("该旅馆你已入住，请勿重复入住!");
                json.setSuccess(false);
                logger.info("该旅馆你已入住，请勿重复入住!");
                return json;
            }

            // base64格式转成Blob二进制
            byte[] photoBytes = null;
            photoBytes = getStringImage(photo);
            // base64格式转成Blob二进制
            byte[] IDPhotoBytes = null;
            IDPhotoBytes = getStringImage(IDPhoto);

            String num = (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10);
            logger.info("RECORDSNO后三位：" + num);


            // 插入有证入住信息
            HashMap<String, Object> sub_map = new HashMap<String, Object>();
            String DJ_LVKEDAIMA = hotelCode + String.valueOf(generate(12));
            sub_map.put("DJ_LVKEDAIMA", DJ_LVKEDAIMA);
            sub_map.put("DJ_XINGMING", name);
            sub_map.put("DJ_XINGBIE", sex);
            sub_map.put("DJ_MINZU", nation);
            sub_map.put("DJ_CHUSHENGRIQI", birth);
            sub_map.put("DJ_ZHENGJIANLEIXING", IDType);
            sub_map.put("DJ_ZHENGJIANHAOMA", IDNumber);
            sub_map.put("DJ_SHENGSHIXIAN", xzqh_id);
            sub_map.put("DJ_XIANGZHI", address);
            sub_map.put("DJ_RUZHUSHIJIAN", time);
            sub_map.put("DJ_RUZHUFANGHAO", roomNumber);
            sub_map.put("DJ_ZHAOPIAN", IDPhotoBytes);
            sub_map.put("DJ_UPZHAOPIAN", photoBytes);
            sub_map.put("DJ_LVGUANDAIMA", hotelCode);
            sub_map.put("BUPLOAD", "3");// 3-已打包 0-未打包
            sub_map.put("RECORDSNO", hotelCode + time.replace("-", "").replace(":", "").replace(" ", "") + num);
            sub_map.put("STATIONID", hotelCode);
            sub_map.put("PACKNAME", hotelCode + time.replace("-", "").replace(":", "").replace(" ", "") + num);
            sub_map.put("TEL", tel);
            sub_map.put("ENTERPRISE_ID", "4");

            /* 2019/1/21 修改,使用一个字段区分是否使用省公司结构上传同步数据*/
            sub_map.put("DJ_TIMAO", "0");//用于同步数据,0:数据有变化,未同步;1:已同步
            logger.info("插入境内入住信息，证件号码为：" + sub_map.get("DJ_ZHENGJIANHAOMA"));

            //20211027 jiangf 新增未成年入住功能
            /*--------------------------------------*/
            if (!AgeCalculation.getAge(birth)) {//如果是未成年人，则额外记录以下信息
                sub_map.put("DJ_JIANHURENXINGMINGM", guardianName);
                sub_map.put("DJ_JIANHURENZHENGJIAN", guardianIDNumber);
                sub_map.put("DJ_JIANHURENDIANHUA", guardianTel);
                sub_map.put("DJ_TONGZHURENGUANXI", residentsRelationship);
                sub_map.put("DJ_GUANXISHIFOUBUHELI", is_unreasonable);
                sub_map.put("DJ_SHIFOUCHUYUWEIXIAN", is_danger);
                sub_map.put("DJ_BUHELIRUZHU", unreasonable_check_in);
                sub_map.put("DJ_QITAKEYIQINGKUANG", other_suspicious_situations);
            }
            /*--------------------------------------*/
            int sub_res = checkInService.insertCheckIn(sub_map);
            logger.info("成功插入境内入住信息" + sub_res);
            if ("0".equals(is_rzsb)) {
                //异步人证认证
                //RzCompare rzCompare=new RzCompare();
                rzCompare.doCompearIDcardAndPhoto(checkInService, DJ_LVKEDAIMA, IDNumber, name, tel, IDPhoto, photo);

            }
            // 更改预订状态为已入住
            String bookTime = request.getParameter("bookTime");
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhh24mmss");// 设置日期格式
            String date = (df.format(new Date())).substring(0, 8);// new Date()为获取当前系统时间
            if (bookTime != null && bookTime != "") {
                bookTime = bookTime.replace("-", "").substring(0, 8);
            } else {
                bookTime = date;
            }
            HashMap<String, Object> sub_map1 = new HashMap<String, Object>();
            sub_map1.put("STATIONID", hotelCode);
            sub_map1.put("ROOMNUMBER", roomNumber);
            sub_map1.put("CHECKINTIME", bookTime);
            logger.info("更改预订状态" + sub_map1);
            int sub_res1 = checkInService.updateBookRoom(sub_map1);
            logger.info("成功更改预订状态" + sub_res1);

            if (sub_res == 1) {
                json.setObj(sub_res);
                json.setMsg("成功入住！");
                logger.info("成功入住！");
                json.setSuccess(true);
            } else {
                json.setObj(sub_res);
                json.setMsg("入住失败！");
                logger.info("入住失败！");
                json.setSuccess(false);
            }

        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("insertCheckIn.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 出入有证入住信息（境外）
     *
     * @return
     */
    @RequestMapping("/insertCheckInF.do")
    @ResponseBody
    public Json insertCheckInF(HttpServletRequest request) {
        Json json = new Json();
        try {
            // 获取前端的值
            String hotelCode = request.getParameter("hotelCode");
            String lastname = request.getParameter("lastname");
            String firstname = request.getParameter("firstname");
            String name = request.getParameter("name");
            String sex = request.getParameter("sex");
            String birth = request.getParameter("birth");
            String national = request.getParameter("national");
            String IDType = request.getParameter("IDType");
            String IDNumber = request.getParameter("IDNumber");
            String VisaType = request.getParameter("VisaType");
            String VisaNumber = request.getParameter("VisaNumber");
            String TLQZ_Time = request.getParameter("TLQZ_Time");
            String VisaOffice = request.getParameter("VisaOffice");
            String RJ_Time = request.getParameter("RJ_Time");
            String RJ_Port = request.getParameter("RJ_Port");
            String JD_Company = request.getParameter("JD_Company");
            String RZ_Time = request.getParameter("RZ_Time");
            String RZ_RoomNumber = request.getParameter("RZ_RoomNumber");
            String From_Where = request.getParameter("From_Where");
            String To_Where = request.getParameter("To_Where");
            String IDPhoto = request.getParameter("IDPhoto");
            String photo = request.getParameter("photo");
            String JD_Person = request.getParameter("JD_Person");
            String remark = request.getParameter("remark");
            String TLSY = request.getParameter("TLSY");
            String ID_Time = request.getParameter("ID_Time");
            String birth_Area = request.getParameter("birth_Area");
            String deposit = request.getParameter("deposit");
			
			/*hotelCode = "5101220060";
			lastname = "gao";
			firstname = "min";
			name = "高敏";
			sex = "1";
			birth = "1994-05-01";
			national = "USA";
			IDType = "11";
			IDNumber = "421182199405013329";
			VisaType = "r";
			VisaNumber = "3329";
			TLQZ_Time = "2019-09-12";
			VisaOffice = "3711";
			RJ_Time = "2018-08-12";
			RJ_Port = "Z060351";
			JD_Company = "成都宾馆";
			RZ_Time = "2018-09-12 12:34:56";
			RZ_RoomNumber = "101";
			From_Where = "USA";
			To_Where = "KOR";
			IDPhoto = "123";
			photo = "123";
			JD_Person = "linsa";
			remark = "lala";
			TLSY = "#15";
			ID_Time = "2028-09-12";
			birth_Area = "USA";
			deposit = "30";*/

            DbUtil.setDb("1");
            //判断当前人是否在该房间已入住
            HashMap<String, Object> map2 = new HashMap<String, Object>();
            map2.put("DJ_ZHENGJIANHAOMA", IDNumber);
            map2.put("DJ_LVGUANDAIMA", hotelCode);
            HashMap<String, String> hashMap2 = checkInService.selectDoYouCheckIn(map2);
            HashMap<String, String> hashMap3 = checkInService.selectDoYouCheckInF(map2);
            if (hashMap2.get("NUM").equals("false") || hashMap3.get("NUM").equals("false")) {
                json.setMsg("该旅馆你已入住，请勿重复入住!");
                json.setSuccess(false);
                logger.info("该旅馆你已入住，请勿重复入住!");
                return json;
            }

            // base64格式转成Blob二进制
            byte[] photoBytes = null;
            photoBytes = getStringImage(photo);
            // base64格式转成Blob二进制
            byte[] IDPhotoBytes = null;
            IDPhotoBytes = getStringImage(IDPhoto);

            String num = (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10);
            logger.info("RECORDSNO后三位：" + num);

            // 插入有证入住信息
            HashMap<String, Object> sub_map = new HashMap<String, Object>();
            sub_map.put("F_LVKEDAIMA", hotelCode + String.valueOf(generate(12)));
            sub_map.put("F_LASTNAME", lastname);
            sub_map.put("F_FIRSTNAME", firstname);
            sub_map.put("F_NAME", name);
            sub_map.put("F_XINGBIE", sex);
            sub_map.put("F_BIRTH", birth);
            sub_map.put("F_GUOJI", national);
            sub_map.put("F_IDTYPE", IDType);
            sub_map.put("F_IDNUMBER", IDNumber);
            sub_map.put("F_QIANZHENGZHONGLEI", VisaType);
            sub_map.put("F_QIANZHENGHAOMA", VisaNumber);
            sub_map.put("F_TINGLIUQIZHI", TLQZ_Time);
            sub_map.put("F_QIANFAJIGUAN", VisaOffice);
            sub_map.put("F_RUJINGRIQI", RJ_Time);
            sub_map.put("F_RUJINGKOUAN", RJ_Port);
            sub_map.put("F_BINGUANID", hotelCode);
            sub_map.put("F_JIEDAIDANWEI", JD_Company);
            sub_map.put("F_RUZHUSHIJIAN", RZ_Time);
            sub_map.put("F_ROOM", RZ_RoomNumber);
            sub_map.put("F_HECHULAI", From_Where);
            sub_map.put("F_QUHECHU", To_Where);
            sub_map.put("F_ZHAOPIAN", IDPhotoBytes);
            sub_map.put("F_UPZHAOPIAN", photoBytes);
            sub_map.put("F_JIEDAIREN", JD_Person);
            sub_map.put("F_BEIZHU", remark);
            sub_map.put("F_CSD", birth_Area);
            sub_map.put("RECORDSNO", hotelCode + RZ_Time.replace("-", "").replace(":", "").replace(" ", "") + num);
            sub_map.put("STATIONID", hotelCode);
            sub_map.put("BUPLOAD", "0");
            sub_map.put("F_TINGLIUSHIYOU", TLSY);
            sub_map.put("F_ZHENGJIANYOUXIAOQI", ID_Time);
            sub_map.put("PACKNAME", hotelCode + RZ_Time.replace("-", "").replace(":", "").replace(" ", "") + num);

            /* 2019/1/21 修改,使用一个字段区分是否使用省公司结构上传同步数据*/
            sub_map.put("F_ZHIYE", "0");//用于同步数据,0:数据有变化,未同步;1:已同步

            logger.info("插入境外入住信息，证件号码为：" + sub_map.get("F_IDNUMBER"));
            int sub_res = checkInService.insertCheckInF(sub_map);
            logger.info("成功插入境外入住信息" + sub_res);

            // 更改预订状态为已入住
            String bookTime = request.getParameter("bookTime");
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhh24mmss");// 设置日期格式
            String date = (df.format(new Date())).substring(0, 8);// new Date()为获取当前系统时间
            if (bookTime != null && bookTime != "") {
                bookTime = bookTime.replace("-", "").substring(0, 8);
            } else {
                bookTime = date;
            }
            HashMap<String, Object> sub_map1 = new HashMap<String, Object>();
            sub_map1.put("STATIONID", hotelCode);
            sub_map1.put("ROOMNUMBER", RZ_RoomNumber);
            sub_map1.put("CHECKINTIME", bookTime);
            logger.info("更改预订状态" + sub_map1);
            int sub_res1 = checkInService.updateBookRoom(sub_map1);
            logger.info("成功更改预订状态" + sub_res1);

            if (sub_res == 1) {
                json.setObj(sub_res);
                json.setMsg("成功入住！");
                logger.info("成功入住！");
                json.setSuccess(true);
            } else {
                json.setObj(sub_res);
                json.setMsg("入住失败！");
                logger.info("入住失败！");
                json.setSuccess(false);
            }

        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("insertCheckInF.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询证件类型（境外）
     *
     * @return
     */
    @RequestMapping("/selectIDTypeF.do")
    @ResponseBody
    public Json selectIDTypeF() {
        Json json = new Json();
        try {
            DbUtil.setDb("1");
            List<HashMap<String, String>> list = checkInService.selectIDTypeF();
            logger.info("成功查询境外证件类型！");
            json.setObj(list);
            json.setMsg("成功查询境外证件类型！");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("selectIDTypeF.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询签证种类（境外）
     *
     * @return
     */
    @RequestMapping("/selectVisaType.do")
    @ResponseBody
    public Json selectVisaType() {
        Json json = new Json();
        try {
            DbUtil.setDb("1");
            List<HashMap<String, String>> list = checkInService.selectVisaType();
            logger.info("成功查询签证种类！");
            json.setObj(list);
            json.setMsg("成功查询签证种类！");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("selectVisaType.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询国籍地区,出生地（境外）
     *
     * @return
     */
    @RequestMapping("/selectNationality.do")
    @ResponseBody
    public Json selectNationality() {
        Json json = new Json();
        try {
            DbUtil.setDb("1");
            List<HashMap<String, String>> list = checkInService.selectNationality();
            logger.info("成功查询国籍地区,出生地！");
            json.setObj(list);
            json.setMsg("成功查询国籍地区,出生地！");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("selectNationality.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询入境口岸（境外）
     *
     * @return
     */
    @RequestMapping("/selectPortofentry.do")
    @ResponseBody
    public Json selectPortofentry() {
        Json json = new Json();
        try {
            DbUtil.setDb("1");
            List<HashMap<String, String>> list = checkInService.selectPortofentry();
            logger.info("成功查询入境口岸！");
            json.setObj(list);
            json.setMsg("成功查询入境口岸！");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("selectPortofentry.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询停留事由（境外）
     *
     * @return
     */
    @RequestMapping("/selectTLSY.do")
    @ResponseBody
    public Json selectTLSY() {
        Json json = new Json();
        try {
            DbUtil.setDb("1");
            List<HashMap<String, String>> list = checkInService.selectTLSY();
            logger.info("成功查询停留事由！");
            json.setObj(list);
            json.setMsg("成功查询停留事由！");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("selectTLSY.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询签发机关（境外）
     *
     * @return
     */
    @RequestMapping("/selectVisaOffice.do")
    @ResponseBody
    public Json selectVisaOffice() {
        Json json = new Json();
        try {
            DbUtil.setDb("1");
            List<HashMap<String, String>> list = checkInService.selectVisaOffice();
            logger.info("成功查询签发机关！");
            json.setObj(list);
            json.setMsg("成功查询签发机关！");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("selectVisaOffice.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询省份或国家（境外）
     *
     * @return
     */
    @RequestMapping("/selectProvinceF.do")
    @ResponseBody
    public Json selectProvinceF() {
        Json json = new Json();
        try {
            DbUtil.setDb("1");
            List<HashMap<String, String>> list = checkInService.selectProvinceF();
            logger.info("成功查询省份或国家列表！");
            json.setObj(list);
            json.setMsg("成功查询省份或国家列表！");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("selectProvinceF.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询市（境外）
     *
     * @return
     */
    @RequestMapping("/selectCityF.do")
    @ResponseBody
    public Json selectCityF(HttpServletRequest request) {
        Json json = new Json();
        try {
            DbUtil.setDb("1");
            String area = request.getParameter("area");
            //area="湖北省";
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("NUM", area.length());
            map.put("DI_CVALUE", area);
            List<HashMap<String, String>> list = checkInService.selectCityF(map);
            logger.info("成功查询市列表！");
            json.setObj(list);
            json.setMsg("成功查询市列表！");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("selectCityF.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 查询县/地区（境外）
     *
     * @return
     */
    @RequestMapping("/selectAreaF.do")
    @ResponseBody
    public Json selectAreaF(HttpServletRequest request) {
        Json json = new Json();
        try {
            DbUtil.setDb("1");
            String area = request.getParameter("area");
            //area="湖北省黄冈市";
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("NUM", area.length());
            map.put("DI_CVALUE", area);
            List<HashMap<String, String>> list = checkInService.selectAreaF(map);
            logger.info("成功查询县/地区列表！");
            json.setObj(list);
            json.setMsg("成功查询县/地区列表！");
            json.setSuccess(true);
        } catch (Exception e) {
            json.setMsg("服务器繁忙,请稍后再试！");
            json.setSuccess(false);
            logger.error("selectAreaF.do-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            e.printStackTrace();
        }
        return json;
    }


    /**
     * 产生随机数
     *
     * @return
     */
    public static char[] generate(int grade) {
        char[] chs = new char[grade];
        // 随机字符范围数组
        char[] letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9'};
        // boolean[] flag=new boolean[letters.length];//默认都存为false
        for (int i = 0; i < chs.length; i++) {
            int index;
            index = (int) (Math.random() * letters.length);
            chs[i] = letters[index];// 基于下标index到letters中选字符
            /*
             * do { index=(int)(Math.random()*letters.length);
             * }while(flag[index]);// 判断生成的字符是否重复
             * chs[i]=letters[index];//基于下标index到letters中选字符 flag[index]=true;
             */
        }
        return chs;
    }

    /**
     * 二进制流转Base64字符串
     *
     * @param data 二进制流
     * @return data
     * @throws IOException 异常
     */
    public static String getImageString(byte[] data) throws IOException {
        BASE64Encoder encoder = new BASE64Encoder();
        return data != null ? encoder.encode(data) : "";
    }

    /**
     * Base64字符串转 二进制流
     *
     * @param base64String Base64
     * @return base64String
     * @throws IOException 异常
     */
    public static byte[] getStringImage(String base64String) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        return base64String != null ? decoder.decodeBuffer(base64String) : null;
    }

}
